<script>
import Vue from "vue";
import { getLogin } from "@/api/login/login";

import { mapGetters } from "vuex";
export default {
  globalData: {
    data: {
      encryptedData: "",
      iv: "",
      parentInviteCode: "",
	  noticecontent:"",
    },
    //用户登录凭证code
    getCode() {
      const than = this;
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: (res) => {
            console.log(res.code, "res code");
            resolve(res.code);
          },
          fail: reject,
        });
      });
    },

    trimAll(ele) {
      if (typeof ele === "string") {
        return ele.split(/[\t\r\f\n\s]*/g).join("");
      } else {
        console.error(
          `${typeof ele} is not the expected type, but the string type is expected`
        );
      }
    },

    // 获取微信用户信息(新版)
    getUserProfile() {
      //获取用户信息 包含appid
      // const appid = uni.getAccountInfoSync();
      // console.log(appid, "appid");
      const app = this;
      //检查登录态是否过期
      // uni.checkSession({
      //   provider: "weixin",
      //   success: function (loginRes) {
      //     console.log("checkSession成功", loginRes);
      //   },
      //   fail: function (loginRes) {
      //     console.log("checkSession失败", loginRes);
      //   },
      // });
      console.log("登录授权开始");
      wx.canIUse("getUserProfile") &&
        wx.getUserProfile({
          lang: "zh_CN",
          desc: "获取用户相关信息",
          async success(res) {
            console.log("用户同意了授权");
            console.log("用户信息:", res);
            const { encryptedData, iv } = res;
            const {
              gender,
              avatarUrl,
              city,
              country,
              language,
              nickName,
              province,
            } = res.userInfo;
            uni.setStorageSync("MyUserInfo", res.userInfo);
            // const code = await app.getCode();
            uni.login({
              provider: "weixin",
              success: async (codeData) => {
                app.data.encryptedData = encryptedData;
                app.data.iv = iv;
                const data = {
                  code: codeData.code,
                  // wxEncryptInfo: {
                  //   encryptedData: app.trimAll(encryptedData),
                  //   iv,
                  // },
                  memberInfo: {
                    avatarUrl: avatarUrl || "",
                    city: city || "",
                    country: country || "",
                    gender: gender || "",
                    language: language || "",
                    nickName: nickName || "",
                    province: province || "",
                  },
                  parentInviteCode:
                    app.data.parentInviteCode ||
                    uni.getStorageSync("parentInviteCode"),
                };
                //登录接口
                const logoData = await getLogin(data);
                console.log(logoData, "提交到后端登录接口");
                if (logoData.code === 0) {
                  // 获取到的当前数据存入缓存
                  const { wxToken, openId, userInfo } = logoData.data;
                  uni.setStorageSync("token", wxToken);
                  uni.setStorageSync("openId", userInfo.wxOpenid);
                  uni.setStorageSync("userInfoServer", userInfo);
                  uni.setStorageSync("userId", userInfo.userId);
                  uni.navigateTo({
                    url: "/pages/empower/mp-weixin",
                  });
                  return true;
                }
              },
              fail: (err) => {
                console.log(err, "登录错误");
              },
            });
          },
          fail() {
            console.log("用户拒绝了授权");
          },
        });
    },
    //推送消息 //授权粉丝新增推送
    pushMesage() {
      uni.getSetting({
        withSubscriptions: true,
        success: (res) => {
          console.log(res, "设置");
          console.log(res.subscriptionsSetting.mainSwitch,'res.subscriptionsSetting.mainSwitch')
          if (!res.subscriptionsSetting.mainSwitch) {
            // 订阅消息的总开关,如果是关着的，引导用户去打开
            this.showPopup = true;
          } else {
            // 如果开着，则继续向下打开弹窗，获取用户授权
            this.messageSubscription();
          }
        },
        fail() {
          this.messageSubscription(); // 如果失败，也打开弹窗，获取用户授权
        },
      });
    },
    //佣金变化推送
     messageCommission() {
      console.log("消息推送开始弹窗确认");
      uni.requestSubscribeMessage({
        tmplIds: ["riO3k_Jqq0oM5CyMEZQ0U8__wWLVd-Upa2SHPL84VGU"],
        success: (res) => {
          console.log("弹窗", res);
          if (res["riO3k_Jqq0oM5CyMEZQ0U8__wWLVd-Upa2SHPL84VGU"] === "accept") {
            // this.sendMsg();
            uni.showToast({
              title: "订阅成功",
              icon: "none",
            });
          }
        },
      });
    },
    //新增粉丝推送
    messageSubscription() {
      console.log("消息推送开始弹窗确认");
      uni.requestSubscribeMessage({
        tmplIds: ["9mWZSibSJB3bkNjiRBQPzb7yqPTQRr8wlw8HKKjIBx0"],
        success: (res) => {
          console.log("弹窗", res);
          if (res["9mWZSibSJB3bkNjiRBQPzb7yqPTQRr8wlw8HKKjIBx0"] === "accept") {
            // this.sendMsg();
            uni.showToast({
              title: "订阅成功",
              icon: "none",
            });
          }
        },
      });
    },
  },
  //检查软件更新
  			updateApp() {
  				let _this = this;
  				//plus.runtime.getProperty 这块是获取当前版本号的
  				plus.runtime.getProperty(plus.runtime.appid, widgetInfo => {
  				//这块是自己封装的请求接口 你们直接按照自己的请求修改即可
				console.log(plus.runtime.appid,widgetInfo)
  // 					this.$api.post(global.apiUrls.publicUpdateAPP, {
  // 						version_name: widgetInfo.version,//这块是我给后端传的当前版本号
  // 						type: 1,//因为我们分 员工端和用户端这块是用来做区分的 你们传参和后端订好字段 按需修改即可
  // 					}).then(res => {
  // 						if (res.data.code == 1 && res.data.data.is_new == 1) {
  // 							//检测当前处于安卓 还是ios
  // 							if (uni.getSystemInfoSync().platform === 'android') {
  // 								_this.wgtUrl = res.data.data.version_url;//赋值最新版本下载地址
  // 								_this.version = res.data.data.version;//赋值最新版本号
  // 								_this.updata = true;//显示更新弹框
  
  // 							} else {
  // 								_this.iosupdata = true;//显示苹果更新弹框
  // 								_this.version = res.data.data.version;//赋值最新版本号
  // 							}
  // 						}
  // 					})
  				});
  			},
  onLaunch: function (options) {
    console.log(options,options.query.v, "App Launch 通过别人分享传递的");
	if(options.query.v){
		 uni.setStorageSync("v", options.query.v);
	}else{
	 uni.setStorageSync("v","VfQkM%2BnjX%2FCyyLQzxk9uEucFvFqGZqE%2FqeoHFHYcpjoaq5idaVCfgXTq6SViWPC03BX7gIBwxnBz%0D%0A7TCLFT7iPpj17YsctT%2BXqaapCjUBe3BHNXJ6wIc2%2FKjv6PyV48jI");	
	}
	 
    if (options.query && options.query.parentInviteCode) {
      uni.setStorageSync("parentInviteCode", options.query.parentInviteCode);
      this.globalData.data.parentInviteCode = options.query.parentInviteCode;
    } else if (options.query && options.query.scene) {
      uni.setStorageSync("parentInviteCode", options.query.scene);
      this.globalData.data.parentInviteCode = options.query.scene;
    }
	var browser={},
	      ua=window.navigator.userAgent;
	    browser.ua=ua;
	    browser.isiPhone=/iphone/ig.test(ua);
	    browser.isiPad=/iPad/ig.test(ua);
	    browser.isAndroid=/ANDROID|X11|ADR/ig.test(ua);//安卓手机
	    browser.isWeiXin=/MicroMessenger/ig.test(ua);//微信端
	    browser.isAlipay=/AlipayDefined/ig.test(ua);//支付宝
	    browser.isIOS=browser.isiPhone||browser.isiPad;//IOS系统
	    window.browserType=browser;
		console.log(browser,"browser")
		
			
			
		if(browser.isWeiXin){
			if(options.query.v){
				uni.reLaunch({
					url:"/pages/subpackage/iswx/index?v="+options.query.v
				})
			}else{
				uni.reLaunch({
					url:"/pages/subpackage/iswx/index"
				})
			}
			
		}
	
	
	
	
  },
  onShow: function () {
    console.log("App Show");
  },
  onHide: function () {
    console.log("App Hide");
  },
};
</script>

<style lang="scss">
@import "uview-ui/index.scss";

@import "static/css/base.css";
@import "static/css/guildford.css";
@import "static/css/style.scss";
@import "static/iconfont/iconfont.css";

/*每个页面公共css */
*,
view,
text,
html,
body {
  box-sizing: border-box;
}
</style>
